<template>
  <div class="app-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="报告标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入报告标题"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="报告类型" prop="reportType">
          <el-select
            v-model="queryParams.reportType"
            placeholder="报告类型"
            clearable
            size="small"
          >
            <el-option label="周报" value="weekly" />
            <el-option label="月报" value="monthly" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 报告列表 -->
    <el-card class="list-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span class="card-title">
          <i class="el-icon-document"></i>
          报告历史
        </span>
        <el-button-group style="float: right">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:report:add']"
            >新增</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete()"
            v-hasPermi="['system:report:remove']"
            >批量删除</el-button
          >
        </el-button-group>
      </div>

      <el-table
        v-loading="loading"
        :data="reportList"
        @selection-change="handleSelectionChange"
        class="report-table"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="报告标题"
          align="center"
          prop="title"
          min-width="200"
        >
          <template slot-scope="scope">
            <div class="report-title">
              <el-tag
                :type="
                  scope.row.reportType === 'weekly' ? 'primary' : 'success'
                "
                size="small"
              >
                {{ scope.row.reportType === "weekly" ? "周报" : "月报" }}
              </el-tag>
              <span class="title-text">{{ scope.row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="报告类型"
          align="center"
          prop="reportType"
          width="100"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.reportType === 'weekly' ? 'primary' : 'success'"
            >
              {{ scope.row.reportType === "weekly" ? "周报" : "月报" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="日期范围"
          align="center"
          prop="dateRange"
          width="200"
        >
          <template slot-scope="scope">
            <span
              >{{
                scope.row.startDate
                  ? parseTime(scope.row.startDate, "{y}-{m}-{d}")
                  : "未设置"
              }}
              至
              {{
                scope.row.endDate
                  ? parseTime(scope.row.endDate, "{y}-{m}-{d}")
                  : "未设置"
              }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="200"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              v-hasPermi="['system:report:query']"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:report:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleDownload(scope.row)"
              v-hasPermi="['system:report:export']"
              >下载</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:report:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 报告详情对话框 -->
    <el-dialog
      title="报告详情"
      :visible.sync="viewDialogVisible"
      width="70%"
      :close-on-click-modal="true"
      :append-to-body="true"
      class="report-dialog"
    >
      <div v-if="currentReport" class="report-detail">
        <div class="report-header">
          <h2>{{ currentReport.title }}</h2>
          <div class="report-meta">
            <el-tag
              :type="
                currentReport.reportType === 'weekly' ? 'primary' : 'success'
              "
            >
              {{ currentReport.reportType === "weekly" ? "周报" : "月报" }}
            </el-tag>
            <span class="meta-item"
              >创建时间：{{ parseTime(currentReport.createTime) }}</span
            >
            <span class="meta-item"
              >日期范围：{{
                currentReport.startDate
                  ? parseTime(currentReport.startDate, "{y}-{m}-{d}")
                  : "未设置"
              }}
              至
              {{
                currentReport.endDate
                  ? parseTime(currentReport.endDate, "{y}-{m}-{d}")
                  : "未设置"
              }}</span
            >
          </div>
        </div>
        <div class="report-content">
          <markdown-preview :content="currentReport.content" />
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleEdit">编辑</el-button>
        <el-button type="success" @click="handleDownload(currentReport)"
          >下载</el-button
        >
      </div>
    </el-dialog>

    <!-- 添加或修改报告对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="80%"
      append-to-body
      class="report-edit-dialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报告标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入报告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报告类型" prop="reportType">
              <el-select v-model="form.reportType" placeholder="请选择报告类型">
                <el-option label="周报" value="weekly" />
                <el-option label="月报" value="monthly" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="form.startDate"
                type="date"
                placeholder="选择开始日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="form.endDate"
                type="date"
                placeholder="选择结束日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="报告内容" prop="content">
          <el-input
            type="textarea"
            v-model="form.content"
            :rows="15"
            placeholder="请输入报告内容，支持Markdown格式"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getReportHistory,
  getReport,
  saveReport,
  updateReport,
  deleteReport,
  batchDeleteReport,
  exportReport,
} from "@/api/report";
import { getToken } from "@/utils/auth";
import { addDateRange, resetForm } from "@/utils/office";
import { parseTime } from "@/utils/office";
import MarkdownPreview from "@/components/MarkdownPreview";

export default {
  name: "ReportHistory",
  components: { MarkdownPreview },
  mixins: [],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报告表格数据
      reportList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        reportType: null,
        createTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "报告标题不能为空", trigger: "blur" },
        ],
        reportType: [
          { required: true, message: "报告类型不能为空", trigger: "change" },
        ],
        startDate: [
          { required: true, message: "开始日期不能为空", trigger: "blur" },
        ],
        endDate: [
          { required: true, message: "结束日期不能为空", trigger: "blur" },
          { validator: this.validateDateRange, trigger: "blur" }
        ],
        content: [
          { required: true, message: "报告内容不能为空", trigger: "blur" },
        ],
      },
      // 查看对话框
      viewDialogVisible: false,
      // 当前查看的报告
      currentReport: null,
      // 导入对话框
      importDialogVisible: false,
      // 文件上传相关
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/report/importData",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 导入全局方法
    addDateRange,
    resetForm,
    /** 查询报告列表 */
    getList() {
      this.loading = true;
      getReportHistory(this.addDateRange(this.queryParams, this.dateRange))
        .then((response) => {
          this.reportList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.$message.error("获取报告列表失败");
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        reportId: null,
        title: null,
        reportType: null,
        startDate: null,
        endDate: null,
        content: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.reportId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row
        ? row.reportId
        : this.ids.length === 1
        ? this.ids[0]
        : null;
      if (!id) {
        this.$message.error("请选择要修改的报告");
        return;
      }
      getReport(id)
        .then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改报告";
        })
        .catch(() => {
          this.$message.error("获取报告详情失败");
        });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.reportId != null) {
            updateReport(this.form)
              .then((response) => {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              })
              .catch(() => {
                this.$message.error("修改报告失败");
              });
          } else {
            saveReport(this.form)
              .then((response) => {
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              })
              .catch(() => {
                this.$message.error("新增报告失败");
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row ? row.reportId : this.ids.length > 0 ? this.ids : null;
      if (!ids) {
        this.$message.error("请选择要删除的报告");
        return;
      }

      const isBatch = Array.isArray(ids);
      const confirmMessage = isBatch
        ? `是否确认删除选中的 ${ids.length} 个报告？`
        : `是否确认删除报告编号为"${ids}"的数据项？`;

      this.$modal
        .confirm(confirmMessage)
        .then(function () {
          if (isBatch) {
            return batchDeleteReport(ids);
          } else {
            return deleteReport(ids);
          }
        })
        .then(() => {
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.error("删除报告失败");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/report/v1/export/list",
        {
          ...this.queryParams,
        },
        `report_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "报告数据导入";
      this.importDialogVisible = true;
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      const fileName = `${row.title}.md`;
      const content = row.content;
      const blob = new Blob([content], { type: "text/markdown" });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = fileName;
      link.click();
      URL.revokeObjectURL(url);
      this.$message.success("下载成功");
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.currentReport = row;
      this.viewDialogVisible = true;
    },
    /** 编辑按钮操作 */
    handleEdit() {
      this.viewDialogVisible = false;
      this.handleUpdate(this.currentReport);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    submitFileForm() {
      this.$refs["upload"].submit();
    },
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        draft: "info",
        published: "success",
        archived: "warning",
      };
      return statusMap[status] || "info";
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        draft: "草稿",
        published: "已发布",
        archived: "已归档",
      };
      return statusMap[status] || "未知";
    },
    // 结束日期不能小于开始日期
    validateDateRange(rule, value, callback) {
      if (!this.form.startDate || !this.form.endDate) {
        callback();
        return;
      }
      if (this.form.startDate > this.form.endDate) {
        callback(new Error("开始日期不能大于结束日期"));
      } else {
        callback();
      }
    },
  },
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 84px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.list-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 按钮组样式 */
.el-button-group {
  display: flex;
  align-items: center;
}

.el-button-group .el-button {
  margin: 0;
  border-radius: 0;
}

.el-button-group .el-button:first-child {
  border-radius: 4px 0 0 4px;
}

.el-button-group .el-button:last-child {
  border-radius: 0 4px 4px 0;
}

/* 表格操作按钮样式 */
.report-table >>> .el-button {
  margin: 2px;
  border-radius: 4px;
}

.report-table >>> .el-button + .el-button {
  margin-left: 5px;
}

.report-table {
  border-radius: 8px;
  overflow: hidden;
}

.report-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-text {
  font-weight: 500;
  color: #2c3e50;
}

.report-dialog >>> .el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.report-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.report-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.report-header h2 {
  margin: 0 0 15px 0;
  font-size: 24px;
  font-weight: 600;
}

.report-meta {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.meta-item {
  font-size: 14px;
  opacity: 0.9;
}

.report-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.report-edit-dialog >>> .el-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.report-edit-dialog >>> .el-textarea__inner {
  font-family: "Monaco", "Menlo", "Ubuntu Mono", monospace;
  font-size: 14px;
  line-height: 1.6;
}

.dialog-footer {
  text-align: right;
  padding: 20px;
  border-top: 1px solid #e9ecef;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .report-meta {
    flex-direction: column;
    gap: 10px;
  }

  .el-table {
    font-size: 12px;
  }

  .report-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style> 